import 'dart:async';
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:qlevar_router/qlevar_router.dart';
import 'package:stacked/stacked.dart';
import '../../heartbeat/helpers/magma_constant.dart';
import '../../heartbeat/helpers/magma_text_style.dart';
import '../../heartbeat/helpers/magma_color.dart';
import '../../heartbeat/helpers/magma_tap.dart';
import '../../heartbeat/helpers/magma_toast.dart';
import '../../comms_link/app_state.dart';
import '../../heartbeat/blueprint/user_model.dart';

/// 视频通话视图模型
class VideoCallNavigatorViewModel extends BaseViewModel {
  String _targetUserId = '';
  String get targetUserId => _targetUserId;

  Timer? _callTimer;
  bool _isCallActive = true;
  bool get isCallActive => _isCallActive;

  /// 获取当前用户
  UserModel? get currentUser => appState.userStore.currentUser;

  /// 检查是否已登录
  bool get isLoggedIn => appState.userStore.isLoggedIn;

  /// 初始化通话数据
  void initializeCallData(String targetUserId) {
    _targetUserId = targetUserId;
    _startCallTimer();
    notifyListeners();
  }

  /// 开始通话计时器
  void _startCallTimer() {
    _callTimer = Timer(const Duration(seconds: 12), () {
      if (_isCallActive) {
        _handleCallTimeout();
      }
    });
  }

  /// 处理通话超时
  void _handleCallTimeout() {
    _isCallActive = false;
    notifyListeners();

    // 发送拨打失败消息
    _sendCallFailedMessage();

    // 延迟返回上一页
    Future.delayed(const Duration(seconds: 2), () {
      QR.back();
    });
  }

  /// 发送拨打失败消息
  Future<void> _sendCallFailedMessage() async {
    if (!isLoggedIn || currentUser == null) return;

    await appState.chatCoordinator.dispatchCallFailedMessage(
      senderId: currentUser!.id,
      receiverId: _targetUserId,
      content:
          'I tried calling you but it seems you\'re busy. Let me know when you\'re free!',
    );
  }

  /// 挂断通话
  void hangUpCall() {
    _isCallActive = false;
    _callTimer?.cancel();
    notifyListeners();

    // 返回上一页
    QR.back();
  }

  @override
  void dispose() {
    _callTimer?.cancel();
    super.dispose();
  }
}

/// 视频通话页面
class VideoCallStory extends StatefulWidget {
  final String targetUserId;

  const VideoCallStory({super.key, required this.targetUserId});

  @override
  State<VideoCallStory> createState() => _VideoCallStoryState();
}

class _VideoCallStoryState extends State<VideoCallStory>
    with TickerProviderStateMixin {
  late AnimationController _breathingController;
  late Animation<double> _breathingAnimation;

  @override
  void initState() {
    super.initState();
    _initializeAnimations();
  }

  /// 初始化动画
  void _initializeAnimations() {
    _breathingController = AnimationController(
      duration: const Duration(seconds: 3),
      vsync: this,
    );

    _breathingAnimation = Tween<double>(begin: 0.9, end: 1.1).animate(
      CurvedAnimation(parent: _breathingController, curve: Curves.easeInOut),
    );

    _breathingController.repeat(reverse: true);
  }

  @override
  void dispose() {
    _breathingController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return ViewModelBuilder<VideoCallNavigatorViewModel>.reactive(
      viewModelBuilder: () => VideoCallNavigatorViewModel(),
      onViewModelReady: (viewModel) {
        viewModel.initializeCallData(widget.targetUserId);
      },
      builder: (context, viewModel, child) {
        final targetUser = appState.userStore.getUserById(widget.targetUserId);

        if (targetUser == null) {
          return Scaffold(
            backgroundColor: MagmaColor.black,
            body: Center(
              child: Text(
                'User not found',
              ).inter(fontSize: 16.sp, color: MagmaColor.white),
            ),
          );
        }

        // 监听通话状态变化，显示超时提示
        if (!viewModel.isCallActive && viewModel.targetUserId.isNotEmpty) {
          WidgetsBinding.instance.addPostFrameCallback((_) {
            MagmaToast.error(context, title: 'Call timeout - No response');
          });
        }

        return Scaffold(
          backgroundColor: MagmaColor.black,
          body: _constructCallInterface(targetUser, viewModel, context),
        );
      },
    );
  }

  /// 构建通话界面
  Widget _constructCallInterface(
    UserModel targetUser,
    VideoCallNavigatorViewModel viewModel,
    BuildContext context,
  ) {
    return Container(
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage(MagmaConstant.background),
          fit: BoxFit.cover,
        ),
      ),
      child: Stack(
        children: [
          // 模糊背景头像
          _buildBlurredAvatarBackground(targetUser),

          // 主要内容
          _buildMainContent(targetUser, viewModel),

          // 挂断按钮
          _buildHangUpButton(viewModel, context),
        ],
      ),
    );
  }

  /// 构建模糊背景头像
  Widget _buildBlurredAvatarBackground(UserModel targetUser) {
    return Positioned.fill(
      child: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage(targetUser.avatar),
            fit: BoxFit.cover,
          ),
        ),
        child: BackdropFilter(
          filter: ImageFilter.blur(sigmaX: 20, sigmaY: 20),
          child: Container(color: MagmaColor.black.withOpacity(0.3)),
        ),
      ),
    );
  }

  /// 构建主要内容
  Widget _buildMainContent(
    UserModel targetUser,
    VideoCallNavigatorViewModel viewModel,
  ) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          // 呼吸效果的头像
          _buildBreathingAvatar(targetUser, viewModel),

          SizedBox(height: 40.h),

          // 通话状态
          Text(
            viewModel.isCallActive
                ? 'Waiting to accept invitation...'
                : 'Call ended',
          ).inter(
            fontSize: 16.sp,
            color: MagmaColor.white.withOpacity(0.8),
            fontWeight: FontWeight.w400,
          ),
        ],
      ),
    );
  }

  /// 构建呼吸效果头像
  Widget _buildBreathingAvatar(
    UserModel targetUser,
    VideoCallNavigatorViewModel viewModel,
  ) {
    return AnimatedBuilder(
      animation: _breathingAnimation,
      builder: (context, child) {
        return Transform.scale(
          scale: viewModel.isCallActive ? _breathingAnimation.value : 1.0,
          child: Container(
            width: 120.w,
            height: 120.w,
            decoration: BoxDecoration(
              shape: BoxShape.circle,
              boxShadow: [
                BoxShadow(
                  color: MagmaColor.white.withOpacity(0.2),
                  blurRadius: 20.r,
                  spreadRadius: 5.r,
                ),
              ],
            ),
            child: CircleAvatar(
              radius: 60.r,
              backgroundImage: AssetImage(targetUser.avatar),
            ),
          ),
        );
      },
    );
  }

  /// 构建挂断按钮
  Widget _buildHangUpButton(
    VideoCallNavigatorViewModel viewModel,
    BuildContext context,
  ) {
    return Positioned(
      bottom: 100.h,
      left: 0,
      right: 0,
      child: Center(
        child: MagmaTap(
          onTap: () {
            MagmaToast.info(context, title: 'Call cancelled by user');
            viewModel.hangUpCall();
          },
          child: Container(
            width: 64.w,
            height: 64.w,
            decoration: BoxDecoration(
              shape: BoxShape.circle,
              image: DecorationImage(
                image: AssetImage(MagmaConstant.handOff),
                fit: BoxFit.cover,
              ),
            ),
          ),
        ),
      ),
    );
  }
}
